<template>
  <div class="schedule-generation">
    <el-card shadow="hover">
      <div class="card-header">
        <h2>排班生成</h2>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" class="generate-form">
        <el-form-item label="排班类型" prop="shift_type_id">
          <el-select v-model="form.shift_type_id" placeholder="请选择排班类型" @change="handleShiftTypeChange">
            <el-option
              v-for="item in shiftTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排班第一人" prop="first_employee_id">
          <el-select v-model="form.first_employee_id" placeholder="请选择排班第一人"
            :disabled="!form.shift_type_id">
            <el-option
              v-for="item in filteredEmployees"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围" prop="date_range">
          <el-date-picker
            v-model="form.date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :picker-options="{
              monthFormat: 'MM',
              lang: 'zh-CN'
            }"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="generateSchedule" :loading="loading">生成排班</el-button>
            <el-button @click="exportSchedule" v-if="schedules.length > 0">导出排班</el-button>
            <el-button @click="fetchShiftTypes">刷新排班类型</el-button>
          </el-form-item>
      </el-form>

      <el-table :data="schedules" style="width: 100%" v-if="schedules.length > 0" height="600px">
        <el-table-column prop="schedule_date" label="日期" width="120"></el-table-column>
        <el-table-column prop="employee_name" label="人员" width="120"></el-table-column>
        <el-table-column prop="shift_type_name" label="排班类型"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" link @click="deleteSchedule(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="no-data" v-else>
        暂无排班数据，请选择排班类型和日期范围后点击生成排班
      </div>


    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '../services/api';

// 状态变量
const shiftTypes = ref([]);
const schedules = ref([]);
const loading = ref(false);
const formRef = ref(null);
const employees = ref([]);
const filteredEmployees = ref([]);
const form = ref({
  shift_type_id: '',
  date_range: [],
  first_employee_id: ''
});
const rules = ref({
  shift_type_id: [{ required: true, message: '请选择排班类型', trigger: 'change' }],
  date_range: [
    {
      required: true,
      message: '请选择日期范围',
      trigger: 'change'
    }
  ],
  first_employee_id: [{ required: true, message: '请选择排班第一人', trigger: 'change' }]
});
// 获取排班类型列表
const fetchShiftTypes = async () => {
  try {
    loading.value = true;
    const response = await api.shiftTypes.getAll();
    shiftTypes.value = response || [];

  } catch (error) {
    ElMessage.error('获取排班类型失败: ' + (error.response?.data?.error || error.message));
    console.error('Failed to fetch shift types:', error);
  } finally {
    loading.value = false;
  }
};

// 获取员工列表
const fetchEmployees = async () => {
  try {
    loading.value = true;
    const response = await api.employees.getAll();
    employees.value = response || [];
  } catch (error) {
    ElMessage.error('获取员工数据失败: ' + (error.response?.data?.error || error.message));
    console.error('Failed to fetch employees:', error);
  } finally {
    loading.value = false;
  }
};

// 处理排班类型变化
const handleShiftTypeChange = async () => {
  // 清空之前的选择
  form.value.first_employee_id = '';
  
  if (form.value.shift_type_id) {
    // 查找当前选择的排班类型
    const currentShiftType = shiftTypes.value.find(
      item => item.id === form.value.shift_type_id
    );
    
    if (currentShiftType) {
      // 根据排班类型筛选员工
      filteredEmployees.value = employees.value.filter(
        employee => employee.type === currentShiftType.applicable_type
      );
    } else {
      filteredEmployees.value = [];
    }
  } else {
    filteredEmployees.value = [];
  }
};

// 获取排班数据
const fetchSchedules = async () => {
  if (!form.value.shift_type_id || form.value.date_range.length < 2) {

    return;
  }

  try {
    const params = {
      shift_type_id: form.value.shift_type_id,
      start_date: form.value.date_range[0],
      end_date: form.value.date_range[1]
    };

    // 添加额外日志，记录完整URL
    const url = `${import.meta.env.VITE_API_URL || '/api'}/schedules?shift_type_id=${params.shift_type_id}&start_date=${params.start_date}&end_date=${params.end_date}`;

    const response = await api.schedules.getAll(params);


    schedules.value = response;
  } catch (error) {
    ElMessage.error('获取排班数据失败: ' + (error.response?.data?.error || error.message));

  }
};

// 生成排班
const generateSchedule = async () => {
  await formRef.value.validate();

  const [start_date, end_date] = form.value.date_range;
  loading.value = true;

  try {
    const response = await api.schedules.generate({
      shift_type_id: form.value.shift_type_id,
      start_date,
      end_date,
      first_employee_id: form.value.first_employee_id
    });

    ElMessage.success('排班生成成功');
    
    // 等待0.5秒后再刷新界面

    await new Promise(resolve => setTimeout(resolve, 500));
    await fetchSchedules();
  } catch (error) {
    ElMessage.error('生成排班失败: ' + (error.response?.data?.error || error.message));
  } finally {
    loading.value = false;
  }
};

// 删除排班记录
const deleteSchedule = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该排班记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await api.schedules.delete(id);
    ElMessage.success('排班记录删除成功');
    await fetchSchedules();
  } catch (error) {
    if (error.name !== 'Error') {
      ElMessage.error('删除排班记录失败: ' + (error.response?.data?.error || error.message));
    }
  }
};

// 导出排班
const exportSchedule = () => {
  // 简单导出为CSV
  const headers = ['日期', '人员', '排班类型'];
  const rows = schedules.value.map(item => [
    item.schedule_date,
    item.employee_name,
    item.shift_type_name
  ]);

  const csvContent = [
    headers.join(','),
    ...rows.map(row => row.join(','))
  ].join('\n');

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', url);
  link.setAttribute('download', `排班表_${form.value.date_range[0]}_${form.value.date_range[1]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 监听表单变化，自动加载排班数据
watch(
  () => [form.value.shift_type_id, form.value.date_range],
  () => {
    fetchSchedules();
  },
  { deep: true }
);

// 页面加载时获取数据
onMounted(() => {
  fetchShiftTypes();
  fetchEmployees();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.generate-form {
  max-width: 800px;
  margin-bottom: 30px;
}

.no-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.log-container {
  margin-top: 30px;
}

.log-content {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.log-content pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  font-family: monospace;
  font-size: 12px;
}
</style>